package com.xuecx.zuul.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.xuecx.common.bean.ResponseBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author:xuecx
 * @CreateDate: 2019/8/4.
 * @QQ:1276162287
 * @Discription:
 */
@Component
public class ErrorFilter extends ZuulFilter {
    Logger logger= LoggerFactory.getLogger(getClass());
    @Override
    public String filterType() {
        return "error";
    }
    @Override
    public int filterOrder() {
        return 0;
    }
    @Override
    public boolean shouldFilter() {
        return true;
    }
    @Override
    public Object run() throws ZuulException {
        sendError(RequestContext.getCurrentContext(),"-1","接口不存在");
        return "接口不存在";
    }
    /**
     * 发送错误消息
     *
     * @param requestContext
     * @param status
     * @param msg
     */
    private void sendError(RequestContext requestContext, String status, String msg) {
        //过滤该请求，不往下级服务转发，到此结束不进行路由
        requestContext.setSendZuulResponse(false);
        HttpServletResponse response = requestContext.getResponse();
        response.setHeader("Content-type", "application/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.write(JSONObject.toJSONString(new ResponseBean(status, msg, null)));
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            pw.close();
        }
    }
}
